package org.xilin

class FamilyController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
    def authenticateService
    def semesterService

    def roles = ''
    def beforeInterceptor = {
        roles = authenticateService.ifAllGranted('ROLE_USER,ROLE_ADMIN')? 'any' : ''
    }
    
    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        //params.max = Math.min(params.max ? params.int('max') : 10, 100)
        render(template: "list", model:[instanceList: Family.list(params), familyInstanceTotal: Family.count()])
    }

    def create = {
        def familyInstance = new Family()
        familyInstance.properties = params
        return [familyInstance: familyInstance]
    }

    def adminCreate = {
        def familyInstance = null
        def userInstance = null

        if (params.id) {
            familyInstance = Family.get(params.id)
            userInstance = User.findByUsername(familyInstance.userId)
        }
        else {
            familyInstance = new Family()
            familyInstance.properties = params
        }
      
        render(template: "adminCreate", model: [familyInstance: familyInstance, userInstance: userInstance])
    }

    def adminSave = {
        def familyInstance = null
        def userInstance = null

        if (params.user.id) {
            userInstance = User.get(params.user.id)
            userInstance.properties = params.user
        }
        else {
            userInstance = new User(params.user)
            userInstance.enabled = true
            userInstance.emailShow = true
            userInstance.description = 'family'
        }

        if (params.id) {
            familyInstance = Family.get(params.id)
            familyInstance.properties = params
        }
        else {
            familyInstance = new Family(params)
        }

        if (!userInstance.validate()) {
            userInstance.errors.allErrors.each {
                log.debug(it)
            }
            flash.message = "Missing required data for Family"
            render(template: params.view, model: [familyInstance: familyInstance, userInstance: userInstance])
            return
        }

        def role = Role.findByAuthority("ROLE_USER")
        role.addToPeople(userInstance)
        role.save(flush:true)
        userInstance.passwd = authenticateService.passwordEncoder(params.user.passwd)
        userInstance.save(flush:true)
        userInstance.refresh()
      
        familyInstance.userId = userInstance.username
        if (familyInstance.save(flush:true)) {
            familyInstance.refresh()
            redirect(action: "list")
        }
        else {
            familyInstance.errors.allErrors.each {
                log.debug(it)
            }
            flash.message = "Missing required data for Family"
            render(template: params.view, model: [familyInstance: familyInstance, userInstance: userInstance])
        }
    }

    def adminEdit = {
        def familyInstance = Family.get(params.id)
        def userInstance = User.findByUsername(familyInstance.userId)
        if (!familyInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'family.label', default: 'family'), params.id])}"
            redirect(action: "list")
        }
        else {
            render(template: "adminEdit", model: [familyInstance: familyInstance, userInstance: userInstance])
        }
    }

    def adminDelete = {
        def familyInstance = Family.get(params.id)
        if (familyInstance) {
            try {
                def username = familyInstance.userId
                familyInstance.delete(flush: true)
                def user = User.findByusername(username)
                def role = Role.findByAuthority("ROLE_USER")
                role.removeFromPeople(user)
                user.delete(flush:true)

                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'family.label', default: 'Family'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'family.label', default: 'Family'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'family.label', default: 'Family'), params.id])}"
            redirect(action: "list")
        }
    }

    def adminShow = {
        def familyInstance = Family.read(params.id)
        if (!familyInstance) {
            render "No family found"
        }
        else {
            render (template:'adminShow', model:[familyInstance: familyInstance])
        }
    }

    def adminPayment = {
        def familyInstance = Family.read(params.id)
        if (!familyInstance) {
            render "No family found"
        }
        else {
            def payments = Payment.findAllByFamilyAndSemester(familyInstance, semesterService.getActiveSemester())
            def totalPayment = 0
            payments.each {
                println ">>> it.amount =" + it.amount
                totalPayment += it.amount
            }
            render (template:'adminPayment', model:[familyInstance: familyInstance, studentList: familyInstance.students, totalPayment:totalPayment])
        }
    }

    def adminMakePayment = {
        Semester semester = semesterService.getActiveSemester()
        Payment payment = new Payment()
        payment.family = Family.read(params.familyId)
        payment.paymentType = params.paymentType
        payment.amount = params.amount as int
        payment.semester = semester
        payment.updatedBy = User.findByUsername(session.user)

      
        def msg = "false"
        if (payment.save(flush:true)) {
          payment.refresh()
          msg = "true"
        }
        else {
          payment.errors.allErrors.each {
              println it
          }
        }
        render msg;
    }

    def save = {
        def familyInstance = new Family(params)
        if (familyInstance.save(flush: true)) {
//            session.family = familyInstance
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'family.label', default: 'Family'), familyInstance.id])}"
//            render(view: "show", params: [id : familyInstance.userId])
            redirect(action: "show", params:params)
        }
        else {
//            render(view: "edit", model: [familyInstance: familyInstance])
            redirect(action: "show", params:params)
        }
    }

    def show = {
        def user = authenticateService.userDomain();
        def familyInstance = Family.findByUserId(user.username)
        if (!familyInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'family.label', default: 'Family'), params.id])}"
            redirect(action: "list")
        }
        else {
            render (template:'show', model:[familyInstance: familyInstance])
        }
    }

    def studentList = {
        def user = authenticateService.userDomain();
        def familyInstance = Family.findByUserId(user.username)
        if (!familyInstance) {
           flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'family.label', default: 'Family'), params.id])}"
           render (template:'studentList', model:[familyInstance: familyInstance])
        }
        else {
            render (template:'studentList', model:[familyInstance: familyInstance])
        }
    }

    def edit = {
        def familyInstance = null
        if(params.id) {
            familyInstance =  Family.findByUserId(params.id)
        } else {
            def user = authenticateService.userDomain()
            familyInstance =  Family.findByUserId(user.username)
        }


        if (!familyInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'family.label', default: 'Family'), params.id])}"
            redirect(action: "list")
        }
        else {
           // return [familyInstance: familyInstance]
           render (template: "edit", model: [familyInstance: familyInstance])
        }
    }

    def update = {
        def familyInstance = Family.findByUserId(params.userId)
        if (familyInstance) {
            familyInstance.properties = params
            User user = User.findByUsername(params.userId)
            if (!familyInstance.hasErrors() && familyInstance.save(flush: true)) {
                if(user && user.email != params.email) {
                    user.email = params.email
                    user.save(flush:true)
                }
//                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'family.label', default: 'Family'), familyInstance.userId])}"
//                render (template:'show', model:[familyInstance: familyInstance, params:params])
                chain(action: "show", params:[id: familyInstance.userId])
            }
            else {
                flash.message = "family save failed!"
//                render(template: "edit", model: [familyInstance: familyInstance])
                render (template:'show', model:[familyInstance: familyInstance])
            }
        } else {
            flash.message = "no family instance found! ${params.id}"
            render (template:'show', model:[familyInstance: familyInstance])
        }
    }

    def delete = {
        def familyInstance = Family.get(params.id)
        if (familyInstance) {
            try {
                familyInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'family.label', default: 'Family'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'family.label', default: 'Family'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'family.label', default: 'Family'), params.id])}"
            redirect(action: "list")
        }
    }
}
